﻿using SoccerGameSpider.DataContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Reflection;
using System.Net;
using System.IO;
using HtmlAgilityPack;
using ScrapperBase;
using System.Diagnostics;
using SoccerGameSpider.Entities;
using System.Globalization;

namespace SoccerGameSpider
{
    public class GermanyScraper : ScraperBase
    {
        //sample: @"http://www.kicker.de/news/fussball/bundesliga/spieltag/1-bundesliga/2005-06/-1/0/spieltag.html";
        private const string MatchUrlFormat = @"http://www.kicker.de/news/fussball/{0}/spieltag/{1}-bundesliga/{2}-{3}/-1/0/spieltag.html";

        protected override Country Country
        {
            get { return ScrapperBase.Country.Germany; }
        }

        protected override int CurrentYear
        {
            get { return DateTime.Now.Month >= 7 ? DateTime.Now.Year : DateTime.Now.Year - 1; }
        }

        protected override int StartYear
        {
            get { return 2005; }
        }

        private const int RoundCount = 34;

        private GameContext db = GameContext.Db;

        protected override void Scrape(League league, int year)
        {
            Trace.TraceInformation("Start the year {0}", year);

            char seq = new char();

            if (char.IsDigit(league.Name[0]))
            {
                seq = league.Name[0];
            }
            else
            {
                seq = '1';
            }

            string season = (year + 1).ToString().Substring(2);

            string url = string.Format(MatchUrlFormat, league.Name, seq, year, season);

            WebClient webClient = new WebClient();
            byte[] buffer = webClient.DownloadData(url);
            MemoryStream stream = new MemoryStream(buffer);

            HtmlDocument mainDoc = new HtmlDocument();
            mainDoc.Load(stream, Encoding.GetEncoding("ISO-8859-1"));

            this.Scrape(league, mainDoc, year);
        }

        private void Scrape(League league, HtmlDocument doc, int year)
        {
            var yearMatches = league.Matches.Where(m => m.MatchTime.Year == year).ToList();
            int maxRound = yearMatches.Count() > 0 ? yearMatches.Max(m => m.Round) : 0;
            int round = maxRound + 1;

            while (round <= RoundCount)
            {
                var matchesNode = doc.DocumentNode.SelectSingleNode("//div[@id='ctl00_PlaceHolderContent_begegnungenCtrl']");
                HtmlNode roundDiv = matchesNode.SelectSingleNode(string.Format("./div[@id='ctrl_begegnungen{0}']", round));
                HtmlNode matchTable = roundDiv.SelectSingleNode(".//table[@summary='Begegnungen']");

                HtmlNodeCollection rows = matchTable.SelectNodes("./tr[contains(@class,'fest')]");

                DateTime matchTime = DateTime.MaxValue;

                DateTime lastDate = DateTime.MinValue;

                foreach (var row in rows)
                {
                    HtmlNodeCollection tds = row.SelectNodes("./td");

                    if (!string.IsNullOrEmpty(HtmlEntity.DeEntitize(tds[1].InnerText).Trim()))
                    {
                        string timeValue = tds[1].InnerText.Replace("&nbsp;", year.ToString() + " ");

                        matchTime = DateTime.Parse(timeValue, CultureInfo.GetCultureInfo("de-DE"));

                        if (lastDate == DateTime.MinValue)
                        {
                            lastDate = matchTime;
                        }

                        if (matchTime < lastDate)
                        {
                            matchTime = matchTime.AddYears(1);
                        }
                    }

                    var match = this.CreateMatch(league, matchTime, row);
                    match.Round = round;

                    GermanyMatchLoader loader = new GermanyMatchLoader();
                    loader.LoadDetail(match);
                    league.Matches.Add(match);
                }

                db.SaveChanges();

                round++;
            }
        }

        private Match CreateMatch(League league, DateTime matchTime, HtmlNode row)
        {
            Match match = new Match();
            match.MatchTime = matchTime;

            var tds = row.SelectNodes("./td");

            string homeName = HtmlEntity.DeEntitize(tds[2].InnerText);
            match.HomeTeam = league.GetTeam(homeName);

            string awayName = HtmlEntity.DeEntitize(tds[4].InnerText);
            match.AwayTeam = league.GetTeam(homeName);

            string[] scores = tds[5].InnerText.Split(new string[] {"&nbsp;"},StringSplitOptions.RemoveEmptyEntries)[0].Split(':');
            match.HomeScore = int.Parse(scores[0]);
            match.AwayScore = int.Parse(scores[1]);

            string link = tds[6].FirstChild.Attributes["href"].Value;

            match.DetailUrl = link.Replace("spielanalyse", "spielverlauf");

            return match;
        }
    }
}
